package namespace.jcu.mobile.library.system;

import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.ParseException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CurrentTransactionActivity extends Activity{

	ArrayList<BookRecord> bookList;
	BookRecord bookUpdater;
	bookListAdapter bookAdapter;
	List<ParseObject> bookRequest;
	List<ParseObject> queryResult;
	String date;
	String month;
	String dueDate;
	int position;
	String url;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Parse.initialize(this, "1GlGZQ1XWU34mHgFyDHZiZRr6HTTSWOZo2nSAowy", "GKVclKTd6TIPxLVPPbDiyvzAMoWA2XLf4ZdZYFwI");
		super.onCreate(savedInstanceState);
		
		
		bookList = new ArrayList<BookRecord>();
		ParseUser currentUser = ParseUser.getCurrentUser();	//get user session
		// if user session still exists
		if(currentUser != null) 
		{
			setContentView(R.layout.insert_newbook);
		
		//merging query from two tables: TransactionRecord & Book
		ParseQuery transactionQuery = new ParseQuery("TransactionRecord");
		transactionQuery.whereEqualTo("LoaneeId", ParseUser.getCurrentUser().getObjectId());	//query when loaneeid = currentuserid
		transactionQuery.whereEqualTo("BookReturned", false);
		ParseQuery bookQuery = new ParseQuery("Book");
		bookQuery.whereMatchesKeyInQuery("objectId", "BookId", transactionQuery);		//finding matches between objectid of book table and bookid of transactionrecord table
		bookQuery.findInBackground(new FindCallback() {
		public void done(List<ParseObject> results, ParseException e) {
			if (e == null)
			{
				Log.d("output_count", String.valueOf(results.size()));		//check output in logcat
				queryResult = results;

				//creating the retrieved results as a book object (using inner class BookRecord)
				for (int i = 0; i < queryResult.size(); i++)
				{
					//date format (1 to display as '1st', 2 as '2nd', 3 as '3rd', etc...)
            		date = null;
            		if (queryResult.get(i).getDate("DueDate").getDate() == 1 || queryResult.get(i).getDate("DueDate").getDate() == 31)
            		{
            			date = String.valueOf(queryResult.get(i).getDate("DueDate").getDate())+"st";
            		}
            		else if (queryResult.get(i).getDate("DueDate").getDate() == 2 || queryResult.get(i).getDate("DueDate").getDate() == 22)
            		{
            			date = String.valueOf(queryResult.get(i).getDate("DueDate").getDate())+"nd";
            		}
            		else if (queryResult.get(i).getDate("DueDate").getDate() == 3 || queryResult.get(i).getDate("DueDate").getDate() == 23)
            		{
            			date = String.valueOf(queryResult.get(i).getDate("DueDate").getDate())+"rd";
            		}
            		else
            		{
            			date = String.valueOf(queryResult.get(i).getDate("DueDate").getDate())+"th";
            		}
            		
            		

		            dueDate = null;
		            dueDate = "Return Date : "+ date+ ", "+getMonthForInt(queryResult.get(i).getDate("DueDate").getMonth());

            	bookUpdater = new BookRecord(queryResult.get(i).getString("BookId"), queryResult.get(i).getString("Title"),
            	queryResult.get(i).getString("Author")+" , "+ String.valueOf(queryResult.get(i).getInt("Publish_Year")),
            	dueDate, ((ParseFile) queryResult.get(i).get("Image")).getUrl().toString());
            	bookList.add(bookUpdater);
				}
			}
			else
			{
				
			}

	        ListView listView = (ListView) findViewById(R.id.ListViewId);
	        listView.setAdapter(bookAdapter);
	        
	        listView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View view, int arg2,long itemID) {
                	setContentView(R.layout.current_loan_detail);
                	
                	position = arg2;
	            	TextView bookDetail = (TextView) findViewById(R.id.bookdetail);
	            	Button renewButton = (Button) findViewById(R.id.request);
					LoaderImageView image = (LoaderImageView) findViewById(R.id.loaderImageView);
					
					image.setImageDrawable(((ParseFile) queryResult.get(arg2).get("Image")).getUrl().toString());
	            	renewButton.setVisibility(1);
					bookDetail.setText(Html.fromHtml("<big><b>"+queryResult.get(arg2).getString("Title")+
	                    	"</b></big><br><br>Author - "+queryResult.get(arg2).getString("Author")+
	                    	"<br><br>Year - "+queryResult.get(arg2).getInt("Publish_Year")+"<br><br>Due Date - "+
	                    	getDateFromInt(queryResult.get(arg2).getDate("DueDate"))+", "+
	                    	getMonthForInt(queryResult.get(arg2).getDate("DueDate").getMonth())+ "<br><br>ISBN - "+
	                    	queryResult.get(arg2).getString("ISBN")));
					
					renewButton.setOnClickListener(new OnClickListener() {
						public void onClick(View v)
						{
							ParseQuery transactionHistory = new ParseQuery("TransactionRecord");
							transactionHistory.whereEqualTo("BookId",queryResult.get(position).getObjectId());
							transactionHistory.whereEqualTo("LoaneeId", ParseUser.getCurrentUser().getObjectId());
							transactionHistory.whereEqualTo("BookReturned", false);
							transactionHistory.getFirstInBackground(new GetCallback() {
								  public void done(ParseObject object, ParseException e) {
								    if (object == null) {
								      Log.d("score", "The getFirst request failed.");
								    } else {
								      if (object.getBoolean("BookRenew") == false)
								      {
                                  		Context context = getApplicationContext();
                                  		CharSequence text = "You've Successfully Renewed This Item. ";
                                  		int duration = Toast.LENGTH_LONG;

                                  		
                                  		//toast message to display when the item is clicked
                                  		Toast toast = Toast.makeText(context, text, duration);
                                  		toast.show();
                                  		object.put("BookRenew", true);
                                  		object.put("RenewDate", new Date());
                                  		object.saveInBackground();
								      }
								      else
								      {
	                                  		Context context = getApplicationContext();
	                                  		CharSequence text = "Sorry, You Can't Renew This Loan. Because You've Already Renewed This Item Once.";
	                                  		int duration = Toast.LENGTH_LONG;

	                                  		
	                                  		//toast message to display when the item is clicked
	                                  		Toast toast = Toast.makeText(context, text, duration);
	                                  		toast.show();
								      }
								    }
								  }
								});						
							}
					});

                }
	        });
		  }
		});
		

        bookAdapter = new bookListAdapter(this, android.R.layout.simple_list_item_1, bookList);
		}
		
		//if user's already logged out
		else
		{
    		Context context = getApplicationContext();
    		CharSequence text = "You must log in to view current loans.";
    		int duration = Toast.LENGTH_LONG;

    		
    		//toast message to display when the item is clicked
    		Toast toast = Toast.makeText(context, text, duration);
    		toast.show();
    		
			Intent i = new Intent(CurrentTransactionActivity.this, LoginActivity.class);
			startActivity(i);
		}

	}
	
	
	//convert month number into month name 
	String getMonthForInt(int m) {
	    String month = "invalid";
	    DateFormatSymbols dfs = new DateFormatSymbols();
	    String[] months = dfs.getMonths();
	    if (m >= 0 && m <= 11 ) {
	        month = months[m];
	    }
	    return month;
	}
	
	String getDateFromInt(Date d)
	{
		String dateNumber;
		if (d.getDate() == 1 || d.getDate() == 31)
		{
			dateNumber = String.valueOf(d.getDate())+"st";
		}
		else if (d.getDate() == 2 || d.getDate() == 22)
		{
			dateNumber = String.valueOf(d.getDate())+"nd";
		}
		else if (d.getDate() == 3 || d.getDate() == 23)
		{
			dateNumber = String.valueOf(d.getDate())+"rd";
		}
		else
		{
			dateNumber = String.valueOf(d.getDate())+"th";
		}
		return dateNumber;
	}
	
	//inner class bookListAdapter of integrating the listadapter with arrays of bookrecord
		public class bookListAdapter extends ArrayAdapter<BookRecord> {
			private ArrayList<BookRecord> bookList;

			public bookListAdapter(Context context, int textViewResourceId, ArrayList<BookRecord> bookList) {
				super(context, textViewResourceId, bookList);
				this.bookList = bookList;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View v = convertView;
				if (v == null) {
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					v = vi.inflate(R.layout.transaction_detail, null);
				}
				
				BookRecord user = bookList.get(position);
				if (user != null) {
					TextView title = (TextView) v.findViewById(R.id.title);
					TextView author = (TextView) v.findViewById(R.id.author);
					TextView available_status = (TextView) v.findViewById(R.id.availableStatus); 

					LoaderImageView image = (LoaderImageView) v.findViewById(R.id.loaderImageView);
					image.setImageDrawable(user.url);
					
					if (title != null) {
						title.setText(user.title);
					}

					if(author != null) {
						author.setText(user.author );
					}
					
					if(available_status != null) {
						available_status.setText(user.returnDate);
					}
					
					
					
				}
				return v;
			}
		}
		
		//inner class to create a bookrecord
		public class BookRecord {
			public String bookId;
			public String title;
			public String author;
			public String returnDate;
			public String url;
			
			public BookRecord(String bookId, String title, String author, String returnDate, String url) {
				this.bookId = bookId;
				this.title = title;
				this.author = author;
				this.returnDate = returnDate;
				this.url = url;
			}
		}
}
